package model.elements.ArtificialIntelligence;

import java.util.Random;

import model.elements.NonPlayerCharacter;
import model.elements.attributes.Coordinate2D;
import model.elements.commands.ElementCommand;
import model.elements.commands.ElementCommandFactory;
import model.elements.states.movement.ElementMovementState;
import model.elements.states.movement.MovingDown;
import model.elements.states.movement.MovingLeft;
import model.elements.states.movement.MovingRight;
import model.elements.states.movement.MovingUp;
import model.exceptions.ModelExceptions;

// TODO: Auto-generated Javadoc
/**
 * The Class MovementWithMesh.
 */
public class MovementWithMesh implements ArtificialIntelligence
{	
	
	/** The m_state. */
	int m_state = 0;
	
	/** The m_last direction. */
	ElementMovementState m_lastDirection;
	
	/** The m_coin flipper. */
	Random m_coinFlipper = new Random(); 
	
	/** The total move turns. */
	int totalMoveTurns;			
	
	/**
	 * Instantiates a new movement with mesh.
	 *
	 * @param i the i
	 */
	public MovementWithMesh(int i) {
		m_lastDirection = getRandomDirection();
		totalMoveTurns = i;
	}
	
	/**
	 * Gets the random direction.
	 *
	 * @return the random direction
	 */
	private ElementMovementState getRandomDirection() {
		switch (m_coinFlipper.nextInt(4)) {
			case 0:
				System.out.print("Voy a la derecha\n");
				return new MovingRight();
			case 1:
				System.out.print("Voy a la izquierda\n");
				return new MovingLeft();
			case 2:
				System.out.print("Voy a la arriba\n");
				return new MovingUp();
			case 3:
				System.out.print("Voy a la abajo\n");
				return new MovingDown();
		}
		return m_lastDirection;		
	}
	
	/**
	 * Movement complete.
	 *
	 * @return true, if successful
	 */
	private boolean movementComplete() {
		if ( m_state < totalMoveTurns ) { 
			++m_state;
			return false;
		}
		m_lastDirection = getRandomDirection();
		m_state = 0;
		return true;
	}
	
	/* (non-Javadoc)
	 * @see model.elements.ArtificialIntelligence.ArtificialIntelligence#getCommand(model.elements.NonPlayerCharacter)
	 */
	@Override
	public ElementCommand getCommand( NonPlayerCharacter nonPlayerCharacter ) throws ModelExceptions {
		
		//TODO hay un bug donde se clippea contra la bomba despues de ponerla a veces. Esto es un fix temporal, comentar para q salte
		nonPlayerCharacter.setPosition(new Coordinate2D(nonPlayerCharacter.getNextPosition().getX(), nonPlayerCharacter.getNextPosition().getY()));
		
		if( movementComplete() && nonPlayerCharacter.canUseWeapon() && m_coinFlipper.nextInt(9) == 0 ) {
			return ElementCommandFactory.getElementUseWeapon();
		}
		
		return ElementCommandFactory.getElementMove( m_lastDirection );
		
	}
	
}